go to previous page   go to home page   go to next page
double A= 0.1, B= -0.1;
DecimalFormat numform = new DecimalFormat(" 000.000;-000.000"); 
System.out.println( "A = " + numform.format(A) );
System.out.println( "B = " + numform.format(B) );

Answer:

A =  000.100
B = -000.100

Collapsing Zeros

The output is somewhat unsatisfactory. It would look better without the leading and trailing zeros

Use the character # in the format string to show a digit that will be omitted from the output string if it is a leading or trailing zero.

For integers: the pattern starts with any number of #s, followed by zero or more 0s. A thousands separator may separate groups of three, as with patterns of zeros. Here are some legal patterns:

####0 
###00 
##0 
000
###0
###,##0

For floating point: The integer part of the pattern follows the rules for integers. If a decimal point is included, the pattern that follows it starts with any number of 0s followed by any number of #s. Here are some legal patterns:

####0.##
##,##0.##   --- first group separated by thousands separator can be short
###00.##
##0.00##
##0.000
000
###0
##0.

Here are some illegal patterns:

0###.##          ---  # can't follow 0 in integer part
##0.0##00        ---  bad fractional part (can't surround #s with 0s)
##00##           ---  bad integer pattern
###0.##0         ---  0 can't follow # in the fractional part
###,##,##0.00    ---  thousands separator with unequal sized groups

Usually format() produces a reasonable string, even with defective format patterns. But seriously defective patterns cause it to throw an IllegalArgumentException at run time. The compiler does not inspect the format patterns, so even if your program compiles, there might be an error in a format pattern. The program might crash at run time.


QUESTION 13:

Is the following format string correct?

000.###